﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using OfficialWeb.Application;
using OfficialWeb.Core;

using OOS.Application.User.Services.Dtos;
using OOS.Application.User.Services.Interfaces;
using OOS.Application.User.Services.Vos;
using OOS.Core.RelyOn;
using OOS.Core.User;

namespace OOS.Application.User.Services
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class UserBasicService:IUserBasicService,ITransient
    {
        private readonly ISqlSugarClient _client;
        private readonly IUserInfoService _userInfoService;

        public UserBasicService(ISqlSugarClient client, IUserInfoService userInfoService)
        {
            _client = client;
            _userInfoService = userInfoService;
        }

        /// <summary>
        /// 新增用户信息
        /// </summary>
        /// <param name="userBasic"></param>
        /// <returns></returns>
        public bool InsertUserBasic(UserBasic userBasic)
        {
            if (userBasic == null) return false;
            //判断token中是否有用户数据
            int userId = JWTToken.GetUser().Id;
            if (userId <= 0) { return false; }
            if (String.IsNullOrEmpty(userBasic.Password)) return false;
            userBasic.Password = MD5Encryption.Encrypt(userBasic.Password);
            userBasic.CreateUser = userId;
            userBasic.CreateDate = DateTime.Now;
            userBasic.UpdateUser = userId;
            userBasic.UpdateDate = DateTime.Now;
            userBasic.IsDeleted = false;
            int userInfoId = _client.Insertable(userBasic).ExecuteReturnIdentity();
            userBasic.Id = userInfoId;
            Boolean flag = this.AddDefaultUserInfo(userBasic);
            if (!flag) return false;
            return userInfoId > 0;
        }

        //生成一个默认的用户个人信息对象
        private bool AddDefaultUserInfo(UserBasic userBasic)
        {
            UserInfo userInfo = new UserInfo();
            userInfo.UserId = userBasic.Id;
            userInfo.Name = userBasic.LoginAccount;
            userInfo.Sex = "保密";
            userInfo.Description = "一句话介绍自己";
            return _userInfoService.InsertUserInfo(userInfo);
        }

        /// <summary>
        /// 根据Id查询查询数据详情(Id -> name)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserBasicDto SelectUserById(int id)
        {
            if (id <= 0) return new UserBasicDto();
            UserBasic user = SelectUserBasicById(id);
            if (user == null) return new UserBasicDto() { Id = id };
            if (user.IsDeleted) return new UserBasicDto() { Id = id };
            UserBasicDto dto = user.Adapt<UserBasicDto>();
            if (user.CreateUser <= 0 && user.UpdateUser <= 0) return dto;
            if (user.CreateUser > 0 && user.UpdateUser > 0)
            {
                List<UserBasic> userBasics = SelectUserBasicByIds([user.CreateUser, user.UpdateUser]);
                if (userBasics.Count <= 0 && userBasics == null) return dto;
                if(userBasics.Count == 1)
                {
                    dto.CreateUser = userBasics[0].Username;
                    dto.UpdateUser = userBasics[0].Username;
                }else
                {
                    if (user.CreateUser <  user.UpdateUser)
                    {
                        dto.CreateUser = userBasics[0].Username;
                        dto.UpdateUser = userBasics[1].Username;
                    }else
                    {
                        dto.CreateUser = userBasics[1].Username;
                        dto.UpdateUser = userBasics[0].Username;
                    } 
                }
                return dto;
            }
            if (user.CreateUser > 0)
            {
                dto.CreateUser = SelectUserById(user.CreateUser).Username;
            }
            if (user.UpdateUser > 0)
            {
                dto.UpdateUser = SelectUserById(user.UpdateUser).Username;
            }
            return dto;
        }

        /// <summary>
        /// 根据id数组查询用户详情数组（数据库原始数据）
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        private List<UserBasic> SelectUserBasicByIds(int[] ids)
        {
            return _client.Queryable<UserBasic>()
                .Where(ub => ids.Contains(ub.Id))
                .ToList();
        }

        /// <summary>
        /// 根据id查询用户详情（数据库原始数据）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private UserBasic SelectUserBasicById(int id)
        {
            return _client.Queryable<UserBasic>()
                .Where(ub => ub.Id == id)
                .Single();
        }

        /// <summary>
        /// 根据id修改用户信息(包含修改密码操作)
        /// </summary>
        /// <param name="userBasic"></param>
        /// <returns></returns>
        public bool UpdateUserBasicById(UserBasic userBasic)
        {
            if (userBasic == null) { return false; }
            //判断token中是否有用户数据
            int userId = JWTToken.GetUser().Id;
            if (userId <= 0) { return false; }
            //数据库中的用户信息
            UserBasic user = SelectUserBasicById(userBasic.Id);
            if (user == null) { return false; }
            user.UpdateUser = userId;
            user.UpdateDate = DateTime.Now;
            //判断密码是否为空，密码为空，不修改密码，密码不为空，修改密码
            if (!String.IsNullOrEmpty(userBasic.Password))
            {
                //密码不为空，修改密码
                user.Password = MD5Encryption.Encrypt(userBasic.Password);
            }
            else
            {
                //密码为空，不修改密码
                user.Username = userBasic.Username;
                user.LoginAccount = userBasic.LoginAccount;
                user.Status = userBasic.Status;
                user.Type = userBasic.Type;
                user.IsDeleted = userBasic.IsDeleted;
            }
            return _client.Updateable(user).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 按条件(用户名模糊查询，登录账号模糊查询，用户状态精确查询,用户类型精确查询)分页查询
        /// </summary>
        /// <param name="userBasic"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageResponseDto<List<UserBasicDto>> SelectByContitionsByPage(UserBasic userBasic, int pageIndex, int pageSize)
        {
            int size = 0;
            List<UserBasicDto> userBasicDtos = _client.Queryable<UserBasic>()
                .Where(ub => ub.IsDeleted == false)
                .WhereIF(!String.IsNullOrEmpty(userBasic.Username), ub => ub.Username.Contains(userBasic.Username))
                .WhereIF(!String.IsNullOrEmpty(userBasic.LoginAccount), ub => ub.LoginAccount.Contains(userBasic.LoginAccount))
                .WhereIF(userBasic.Type != 0, ub => ub.Type == userBasic.Type)
                .WhereIF(userBasic.Status != 0, ub => ub.Status == userBasic.Status)
                .OrderBy(ub => ub.CreateDate,OrderByType.Desc)
                .ToPageList(pageIndex, pageSize,ref size)
                .Adapt<List<UserBasicDto>>();

            for (int i = 0; i < userBasicDtos.Count;i++)
            {
                userBasicDtos[i] = SelectUserById(userBasicDtos[i].Id);
            }

            PageResponseDto<List<UserBasicDto>> pageResponseDto = new PageResponseDto<List<UserBasicDto>>();
            pageResponseDto.data = userBasicDtos;
            pageResponseDto.size = size;
            return pageResponseDto;
                
        }

        /// <summary>
        /// 根据id删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteUserBasicById(int id)
        {
            if (id <= 0) return false;
            UserBasic userBasic = SelectUserBasicById(id);
            userBasic.Password = null;
            userBasic.IsDeleted = true;
            return UpdateUserBasicById(userBasic);
        }

        /// <summary>
        /// 生成用户Token
        /// </summary>
        /// <param name="userBasic"></param>
        /// <returns></returns>
        private String GenerateToken(UserBasic userBasic)
        {
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {
                //用户Id,UserName,LoginAccount存入Token
                {nameof(userBasic.Id), userBasic.Id}
            });
            // 获取刷新 token
            var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 60 * 12);
            // 设置响应报文头
            if (App.HttpContext != null)
            {
                App.HttpContext.Response.Headers["access-token"] = accessToken;
                App.HttpContext.Response.Headers["x-access-token"] = refreshToken;
            }
            return accessToken;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginVo"></param>
        /// <param name="flag">
        /// true,PC端用户登录
        /// false,移动端用户登录
        /// </param>
        /// <returns></returns>
        public LoginDto Login(LoginVo loginVo, Boolean flag)
        {
            if (loginVo == null) return new LoginDto { IsSuccess = false };
            if (String.IsNullOrEmpty(loginVo.LoginAccount) || String.IsNullOrEmpty(loginVo.Password))
            {
                return new LoginDto
                {
                    IsSuccess = false,
                    Message = "登录账号或密码不能为空",
                };
            }
            List<UserBasic> userBasics = this.SelectUserBasicByLoginAccount(loginVo.LoginAccount);
            if (userBasics == null || userBasics.Count <= 0)
            {
                return new LoginDto
                {
                    IsSuccess = false,
                    Message = "该用户不存在",
                };
            }
            foreach (var userBasic in userBasics)
            {
                if (!userBasic.Status.Equals(1))
                {
                    return new LoginDto
                    {
                        IsSuccess = false,
                        Message = "用户已禁用",
                    };
                }
                if (userBasic.Type.Equals(1) && flag)
                {
                    return new LoginDto
                    {
                        IsSuccess = false,
                        Message = "该用户无权限登录后台管理系统",
                    };
                }
                if (userBasic.Password.Equals(MD5Encryption.Encrypt(loginVo.Password)))
                {
                    return new LoginDto
                    {
                        accessToken = this.GenerateToken(userBasic),
                        IsSuccess = true,
                        UserId = userBasic.Id,
                        Message = "登录成功"
                    };
                }
            }
            return new LoginDto
            {
                IsSuccess = false,
                Message = "密码错误",
            };
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="loginVo"></param>
        /// <returns></returns>
        public LoginDto Register(LoginVo loginVo)
        {
            if (loginVo == null) return new LoginDto { IsSuccess = false };
            if (String.IsNullOrEmpty(loginVo.LoginAccount) || String.IsNullOrEmpty(loginVo.Password))
            {
                return new LoginDto
                {
                    IsSuccess = false,
                    Message = "登录账号或密码不能为空",
                };
            }
            List<UserBasic> userBasics = this.SelectUserBasicByLoginAccount(loginVo.LoginAccount);
            Boolean flag = false;
            foreach (var userBasic in userBasics)
            {
                if (userBasic.Password.Equals(MD5Encryption.Encrypt(loginVo.Password))) flag = true;
            }
            if(!flag) {
                UserBasic userBasic = new UserBasic();
                userBasic.Username = loginVo.LoginAccount;
                userBasic.LoginAccount = loginVo.LoginAccount;
                userBasic.Password = MD5Encryption.Encrypt(loginVo.Password);
                userBasic.Type = 1;
                userBasic.Status = 1;
                userBasic.IsDeleted = false;
                userBasic.CreateDate = DateTime.Now;
                userBasic.UpdateDate = DateTime.Now;
                int userId = _client.Insertable(userBasic).ExecuteReturnIdentity();
                UserBasic user = this.SelectUserBasicById(userId);
                this.AddDefaultUserInfo(user);
                user.CreateUser = userId;
                user.UpdateUser = userId;
                user.UpdateDate = DateTime.Now;
                return new LoginDto
                {
                    IsSuccess = _client.Updateable(user).ExecuteCommand() > 0,
                    Message = "注册成功"
                };
            }
            //该用户已存在
            return new LoginDto
            {
                IsSuccess = false,
                Message = "该用户已存在",
            };
        }

        /// <summary>
        /// 根据用户账号精确查询用户信息
        /// </summary>
        /// <param name="loginAccount"></param>
        /// <returns></returns>
        private List<UserBasic> SelectUserBasicByLoginAccount(string loginAccount)
        {
            return _client.Queryable<UserBasic>()
                .Where(ub => ub.IsDeleted == false)
                .Where(ub => ub.LoginAccount == loginAccount)
                .ToList();
        }
    }
}
